package com.wtwd.campus.adapter;

import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.entity.VerifyResult;
import com.wtwd.campus.method.DeleteEncrypt;
import com.wtwd.campus.method.PostPutEncrypt;
import com.wtwd.campus.service.RedisService;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @Author ldaoliang
 * @Date create in 10:13 2021/7/5
 * @Description
 */
public class WebVerifyAdapter extends VerifyAdapter {

    public WebVerifyAdapter(HttpServletRequest request) {
        super(request);
        String url = request.getRequestURI();
        if (url.contains("importDeviceInfo") || url.contains("importCustomerDeviceInfo") || url.contains("uploadLogoImg") || url.contains("excel")||url.contains("importStudentsInfo")) {
            encryptVerify = null;
        } else {
            String method = request.getMethod();
            if (method.equalsIgnoreCase(VerifyAdapter.delete)) {
                encryptVerify = new DeleteEncrypt();
            } else if (method.equalsIgnoreCase(VerifyAdapter.post) || method.equalsIgnoreCase(VerifyAdapter.put)) {
                encryptVerify = new PostPutEncrypt();
            } else if (method.equalsIgnoreCase(VerifyAdapter.get)) {
                encryptVerify = null;
            }
        }
    }

    @Override
    public VerifyResult verifyEncrypt(HttpServletRequest request, RedisService redisService) {
        if("123456".equalsIgnoreCase(sign)){
            return null;
        }
        if (encryptVerify == null) {
            VerifyResult verifyResult = new VerifyResult();
            if (StringUtils.isBlank(managerToken)) {
                verifyResult.setResult(false);
                verifyResult.setRespCode(RespCode.TOKEN_UNAUTHORIZED);
                return verifyResult;
            }
            // 获取token对应的东西
            Map<Object, Object> userMsg = redisService.getUserMsgByToken(managerToken);
            if (userMsg.isEmpty()) {
                verifyResult.setResult(false);
                verifyResult.setRespCode(RespCode.TOKEN_UNAUTHORIZED);
                return verifyResult;
            }
            String currentToken = (String) userMsg.get("current_token");
            if (!managerToken.equals(currentToken)) {
                verifyResult.setResult(false);
                verifyResult.setRespCode(RespCode.TOKEN_CONFLICT);
                return verifyResult;
            }
            return null;
        }
        return encryptVerify.verify(sign, managerToken, request, redisService);
    }

}
